package com.example.mallproduct.exceptionHandler;

import com.common.utils.R;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author guanglin.ma
 * @date 2023-12-04 14:46
 */
@ResponseBody
@ControllerAdvice(value = {"com.example.mallproduct.controller"})
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidExecption(MethodArgumentNotValidException methodArgumentNotValidException) {
        Map map = new HashMap<>();
        for (FieldError fieldError : methodArgumentNotValidException.getBindingResult().getFieldErrors()) {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return R.error(BizCodeEnume.VALIDATED.getCode(), BizCodeEnume.VALIDATED.getMessage()).put("data", map);
    }

//    @ExceptionHandler(value = Exception.class)
//    public R handlerExecption(Exception exception) {
//        System.out.println("错误：");
//        System.out.println(exception);
//        return R.error(400, "未知异常信息").put("data", exception.getMessage());
//    }

//    @ExceptionHandler(value = Throwable.class)
//    public R handlerThrowableExecption(Throwable throwable) {
//        System.out.println(throwable);
//        return R.error(BizCodeEnume.OTHER.getCode(), BizCodeEnume.OTHER.getMessage()).put("data", throwable.getMessage());
//    }
}
